package wei;
import wei.Entity.Course;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CourseServlet")
public class CourseServlet extends HttpServlet {

    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyDSTest";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        CourseRequest(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {

    }
    private void CourseRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        EntityManager em = getEntityManager();

        EntityTransaction tx = em.getTransaction();

        try {


            int courseid =Integer.parseInt(request.getParameter("courseid"));
            String courseName = request.getParameter("courseName");
            String courseType= request.getParameter("courseType");
            int credit =Integer.parseInt(request.getParameter("credit"));

            Course cou = new Course(courseid,courseName, courseType,credit);


            tx.begin();

            em.persist(cou);

            tx.commit();


        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            em.close();
        }

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println("添加课程记录成功");

        response.sendRedirect("Course.jsp");
    }

}
